import request from '@/utils/request';
import { setToken } from '@/utils/storage';
import { AppDispatch } from '..';
import { loadProfileAPI, editProfileAPI } from './../../api/user';
import { editPhotoAPI } from '@/api/user';
import { RootState } from '@/store';
import Profile from './../../pages/Profile/index';
import { ProfileInfo } from '../reducer/user';

export const sendCode = (mobile: string) => {
  return async (dispatch: AppDispatch) => {
    await request({
      url: `/v1_0/sms/codes/${mobile}`,
    });
  };
};

export const authorizations = ({ mobile, code }: { mobile: string; code: string }) => {
  return async (dispatch: AppDispatch) => {
    const res = await request({
      url: '/v1_0/authorizations',
      method: 'post',
      data: { mobile, code },
    });
    dispatch({
      type: 'user/saveAuthor',
      payload: res.data,
    });
    setToken(res.data);
  };
};

/** 获取用户信息  */
export const getUserInfo = () => {
  return async (dispatch: AppDispatch) => {
    const res = await request({ url: '/v1_0/user' });
    dispatch({ type: 'user/saveUserInfo', payload: res.data });
  };
};

/** 获取个人资料 */
export const getProfileInfo = () => {
  return async (dispatch: AppDispatch) => {
    const res = await loadProfileAPI();
    dispatch({ type: 'user/saveProfile', payload: res.data });
  };
};

export const editUserPhoto = (formData: FormData) => {
  return async (dispatch: AppDispatch, getState: () => RootState) => {
    const res = await editPhotoAPI(formData);
    dispatch({
      type: 'user/saveProfile',
      payload: {
        ...getState().user.profile,
        ...res.data,
      },
    });
  };
};

export const editUserProfile = (data: Partial<ProfileInfo>) => {
  return async (dispatch: AppDispatch, getState: () => RootState) => {
    await editProfileAPI(data);
    dispatch({
      type: 'user/saveProfile',
      payload: {
        ...getState().user.profile,
        ...data,
      },
    });
  };
};
